const bookingOrderDao = require('../database/BookingOrderDao');
const meetingRoomDao = require('../database/MeetingRoomDao');
const authMiddleware = require('../middleware/AuthMiddleWare');
const { success, fail } = require('../utils/response');

const onlineUsers = require('../utils/onlineUsers').getOnlineUsers();
const { getIo } = require('../socket');

const router = require('express').Router();

// 创建新订单
router.post('/add', authMiddleware.isAuthenticated, async (req, res) => {
  try {
    const { roomId, startTime, endTime, participantNum } = req.body;
    const customerId = req.user.userId;
    
    // 检查会议室是否存在且可用
    const room = await meetingRoomDao.getRoomById(roomId);
    if (!room) {
      return res.status(404).json(fail(4000, '会议室不存在'));
    }
    
    if (room.status !== '空闲') {
      return res.status(400).json(fail(4000, '会议室当前不可预订'));
    }
    
    // 创建订单（初始状态为"锁定"）
    const orderId = await bookingOrderDao.createBookingOrder({
      customerId,
      roomId,
      startTime,
      endTime,
      participantNum,
      orderStatus: '锁定',
      paymentTime: null
    });
    
    // 更新会议室状态为"锁定"
    await meetingRoomDao.updateRoomStatus(roomId, '锁定');
    
    const io = getIo();
    const socketId = onlineUsers[req.user.userId];
    if (socketId) {
      io.to(socketId).emit('server:order-created', {
        orderId,
        message: '订单已创建'
      });
    }
    res.status(201).json(success({ message: '订单创建成功', orderId }));
  } catch (error) {
    res.status(500).json(fail(5000, '创建订单失败'));
  }
});

// 获取用户订单列表
router.get('/my', authMiddleware.isAuthenticated, async (req, res) => {
  try {
    const customerId = req.user.userId;
    const orders = await bookingOrderDao.getOrdersByCustomerId(customerId);
    res.json(success(orders));
  } catch (error) {
    res.status(500).json(fail(5000, '获取订单列表失败'));
  }
});

// 订单支付
router.post('/:id/pay', authMiddleware.isAuthenticated, async (req, res) => {
  try {
    const orderId = req.params.id;
    const order = await bookingOrderDao.getOrderById(orderId);

    if (!order) {
      return res.status(404).json(fail(4001, '订单不存在'));
    }

    if (order.customer_id !== req.user.userId) {
      return res.status(403).json(fail(4001, '无权操作此订单'));
    }

    if (order.order_status !== '锁定') {
      return res.status(400).json(fail(4001, '订单状态不可支付'));
    }

    // 更新订单状态并记录支付时间
    const result = await bookingOrderDao.updateOrderToPaid(orderId);

    if (result) {
      const io = getIo();
      const socketId = onlineUsers[req.user.userId];
      if (socketId) {
        io.to(socketId).emit('server:order-paid', {
          orderId,
          message: '订单已支付'
        });
      }
      res.json(success({ message: '支付成功' }));
    } else {
      res.status(404).json(fail(4001, '支付失败'));
    }
  } catch (error) {
    console.error('支付失败:', error);
    res.status(500).json(fail(5000, '支付失败'));
  }
});

// 获取订单详情（需要登录）
router.get('/:id', authMiddleware.isAuthenticated, async (req, res) => {
  try {
    const orderId = req.params.id;
    const order = await bookingOrderDao.getOrderById(orderId);
    // console.log(order);

    if (order) {
      res.json(success(order));
    } else {
      res.status(404).json(fail(4001, '订单不存在'));
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(500).json(fail(5000, '获取订单详情失败'));
  }
});

// 取消订单（无需登录，客户没有及时支付自动取消）
router.post('/:id/cancel', async (req, res) => {
  try {
    const orderId = req.params.id;

    // 获取订单信息
    const order = await bookingOrderDao.getOrderById(orderId);
    if (!order) {
      return res.status(404).json(fail(4001, '订单不存在'));
    }

    // 仅允许取消“锁定”状态的订单
    if (order.order_status !== '锁定') {
      return res.status(400).json(fail(4001, '只有锁定状态的订单可以取消'));
    }

    // 调用 DAO 方法取消订单并释放会议室
    const result = await bookingOrderDao.cancelBookingOrder(orderId);

    if (result) {
      res.json(success({ message: '订单已取消，会议室已释放' }));
    } else {
      res.status(404).json(fail(4001, '取消订单失败'));
    }
  } catch (error) {
    console.error('取消订单失败:', error);
    res.status(500).json(fail(5000, '取消订单失败'));
  }
});

module.exports = router;